package com.example.inventory.messaging.producer;

import com.example.inventory.messaging.message.OrderStockReservedMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * 库存事件生产者
 * 负责发送库存相关的 Kafka 消息
 * 
 * @author mall-team
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InventoryEventProducer {

    private final KafkaTemplate<String, Object> kafkaTemplate;

    /**
     * Kafka Topic 常量
     */
    private static final String TOPIC_ORDER_STOCK_RESERVED = "order_stock_reserved";

    /**
     * 发送订单库存预留成功事件
     * 
     * @param message 库存预留消息
     */
    public void sendOrderStockReservedEvent(OrderStockReservedMessage message) {
        log.info("准备发送库存预留成功事件: orderNo={}", message.getOrderNo());
        
        CompletableFuture<SendResult<String, Object>> future = 
            kafkaTemplate.send(TOPIC_ORDER_STOCK_RESERVED, message.getOrderNo(), message);
        
        future.whenComplete((result, ex) -> {
            if (ex == null) {
                log.info("库存预留成功事件发送成功: topic={}, partition={}, offset={}, orderNo={}", 
                    result.getRecordMetadata().topic(),
                    result.getRecordMetadata().partition(),
                    result.getRecordMetadata().offset(),
                    message.getOrderNo());
            } else {
                log.error("库存预留成功事件发送失败: orderNo={}, error={}", 
                    message.getOrderNo(), ex.getMessage(), ex);
            }
        });
    }
}

